# -*- coding: utf-8 -*-

#PBAR_ZspecBasic_Exploratory.py
import matplotlib.pyplot as plt;
import PBAR_Zspec;
import PBAR_Cargo
import os

baseDir = 'C:\Users\jkwong\Documents\Work\PBAR\data3'
prefixList = ['4660-FDFC']
timesliceList = [np.arange(1075)]
timesliceList = [np.arange(2159)]

(energy, dat) = PBAR_Zspec.ReadZspecBasicScan(baseDir, prefixList, timesliceList)

# Calculate some basic discriminates

index = 0
badDetectors = find(dat[index].sum(0).sum(1) == 0)
goodDetectors = find(dat[index].sum(0).sum(1) != 0)

# read in the cargo image
cargoImageFilename = 'PBAR-20130822015.cargoimage'
(cargoImage,bpp,formatt,flag,low1,high1,low2,high2) = PBAR_Cargo.ReadCargoImage(os.path.join(baseDir, cargoImageFilename))


# Plot total counts as function of detector (collapse in time and energy)2
index = 0
plt.figure();
plt.plot(np.arange(1, 137), dat[index].sum(0).sum(1))

plt.xlabel('Detectpr Number')
plt.ylabel('Total Counts');
plt.title(prefixList[index])


# SHOW THE RAW IMAGE, COUNTS
index = 0

def onclick(event):
    print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(event.button, event.x, event.y, event.xdata, event.ydata)

fig = plt.figure(99);
cid = fig.canvas.mpl_connect('button_press_event', onclick)

plt.imshow(dat[index].sum(2).T, interpolation = 'nearest', aspect='auto')
plt.colorbar()

plt.xlabel('Time Slice')
plt.ylabel('Detector Number');
plt.title(prefixList[index])


# show spectra fora particular time bin
plt.figure()
plt.grid()
x = 322
y = 65
plt.plot(energy[index],dat[index][x,y,:])
plt.title("{}, {}".format(x, y))

# SHOW THE RAW IMAGE, BIN MEAN
index = 0
plt.figure();
plt.imshow(dat[index][:,goodDetectors,:].sum(2).T, interpolation = 'nearest', aspect='auto')
plt.colorbar()

plt.xlabel('Time Slice')
plt.ylabel('Detector Number');
plt.title(prefixList[index])



